package com.itmate.webpro.vertx;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.itmate.webpro.HealthStateMsg;
import com.itmate.webpro.config.VertxConfig;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.WebSocketFrame;
import io.vertx.core.json.JsonObject;


public class ConsumerHttpServerVerticle extends AbstractVerticle {
    private long timerID;
    private HttpClient client = null;
    private Boolean isConnection = false;
    
    private static final Logger logger = LoggerFactory
            .getLogger(ConsumerHttpServerVerticle.class);
    
    public void start() {
        System.out.println("socket start");
        initHttpClient();

        //尝试重连
        vertx.setPeriodic(5000, id -> {
            if (!isConnection) {
                initHttpClient();
            }
        });
    }

    private void initHttpClient() {
        if (Objects.nonNull(client)) {
            client.close();
            client = null;
        }
        client = vertx.createHttpClient();
        websocketHandler();
    }

    private void websocketHandler() {
    	System.out.println(" 服务器连接成功。");
    	
        client.websocket(VertxConfig.PORT, VertxConfig.IP, VertxConfig.THIRD_PARTY_URI_PATH, ws -> {
            System.out.println("服务器连接订阅数据成功。");
           // System.out.println("ws: " + ws.textHandlerID());
            isConnection = true;
            //发送心跳
            JsonObject pingMsg = new JsonObject().put("type", "ping");
            ws.writeFrame(WebSocketFrame.textFrame(pingMsg.encode(), true));

            
            timerID = vertx.setPeriodic(5000, id -> {
                ws.writeFrame(WebSocketFrame.textFrame(pingMsg.encode(), true));
            });

            //发送需要订阅数据的地址，仅支持文档中的订阅地址: equipment.realTimeData、equipment.healthStatus、equipment.alarm
            JsonObject registerDataMsg = new JsonObject().put("type", "register").put("address", VertxConfig.REAL_TIME_DATA_ADDRESS);
            ws.writeFrame(WebSocketFrame.textFrame(registerDataMsg.encode(), true));
            
             registerDataMsg = new JsonObject().put("type", "register").put("address", VertxConfig.HEALTH_STATUS_ADDRESS);
             ws.writeFrame(WebSocketFrame.textFrame(registerDataMsg.encode(), true));
             
             registerDataMsg = new JsonObject().put("type", "register").put("address", VertxConfig.ALARM_ADDRESS);
            ws.writeFrame(WebSocketFrame.textFrame(registerDataMsg.encode(), true));
            
            //ZT的检测值
            registerDataMsg = new JsonObject().put("type", "register").put("address", VertxConfig.EQUIPMENT_MODELESTATUS);
            ws.writeFrame(WebSocketFrame.textFrame(registerDataMsg.encode(), true));
            
            registerDataMsg = new JsonObject().put("type", "register").put("address", VertxConfig.EQUIPMENT_PLATEN_REAL_DATA);
            ws.writeFrame(WebSocketFrame.textFrame(registerDataMsg.encode(), true));
            
            ws.handler(buffer -> {
                //接受到的订阅地址的数据
                Map receiveData = JSONObject.parseObject(buffer.toString(), Map.class);
                //logger.info(receiveData+"");
                //System.out.println("receiveData: " + receiveData.get("body"));
                
                Map bodyMap = (Map)receiveData.get("body");
                HandData(bodyMap);
                
            });

            ws.closeHandler(close -> {
                //连接关闭的处理
                isConnection = false;
                vertx.cancelTimer(timerID);
            });
        }, wsErr -> {
            //连接失败，需要做的处理
            System.out.println("服务器连接失败，原因：" + wsErr.getMessage() + "，时间：" + System.currentTimeMillis());
            isConnection = false;
            vertx.cancelTimer(timerID);
        });
    }
    
    private void HandData(Map map)
    {
    	
    	///健康值
    	if(map.containsKey("status") && !map.containsKey("event"))
    	{
    		if(map.containsKey("id"))
    		{
    			String idValue = map.get("id").toString();
    			Map<String,Map> equipment1_data = HealthStateMsg.GetInstance().equipment_data;
    			equipment1_data.put(idValue.toString(), map);
    		}
    		
    	}
    	//else if(map.containsKey("time"))
    	//{
    		//logger.info(map+"");
    	//}
    	
    	//实时值、ZT、和报警直接推送
    	else
    	{
    		try {
    			//logger.info(map+"");
				/*
				 * if(map.containsKey("name")) { String _name = map.get("name").toString();
				 * if(_name.contains("503#")) { //logger.info("aaaaaaaaaaaaaaaaaaaaaaaa"); } }
				 */
				//WebsocketServer.SendAllUserMessage("" + map);
    			if(map.containsKey("event"))
    			{
    				
    				logger.info(map+"");
    			}
    			
    			
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    }


}
